package com.tcm.day03;

/**
 * 合并两个链表
 * https://leetcode.cn/problems/merge-two-sorted-lists/?envType=problem-list-v2&envId=linked-list
 */
public class Code07_CombineLinkedList {

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {

        if (list1 == null) return list2;
        else if (list2 == null) return list1;

        ListNode dummy = new ListNode(-1);
        ListNode cur = dummy;

        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                cur.next = list1;
                list1 = list1.next;
            } else {
                cur.next = list2;
                list2 = list2.next;
            }
            cur = cur.next;
        }

        if (list1 != null) {
            cur.next = list1;
        } else if (list2 != null) {
            cur.next = list2;
        }
        return dummy.next;

    }

    public ListNode mergeTwoLists2(ListNode list1, ListNode list2) {

        if (list1 == null) return list2;
        else if (list2 == null) return list1;

        ListNode head = list1.val <= list2.val ? list1 : list2;
        ListNode prev = head;
        ListNode cur1 = head.next;
        ListNode cur2 = head == list1 ? list2 : list1;

        while (cur1 != null && cur2 != null) {
            if (cur1.val <= cur2.val) {
                prev.next = cur1;
                cur1 = cur1.next;
            } else {
                prev.next = cur2;
                cur2 = cur2.next;
            }
            prev = prev.next;
        }
        prev.next = cur1 != null ? cur1 : cur2;
        return head;
    }

}
